package com.kbbywyclient.util.customservice;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.kbbywyclient.app.Key;
import com.kbbywyclient.data.model.AddressModel;
import com.kbbywyclient.data.model.base.BaseModel;
import com.kbbywyclient.util.LogUtil;
import com.kbbywyclient.util.RSAUtil;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by FHW
 * on 2017/3/24
 */

//CustomGsonResponseBodyConverter.java
final class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String valueStr = value.string();//只能调用一次
        //解密
        String response = RSAUtil.decryptByPrivateKey(valueStr, Key.privateKey);
        if (response == null) {
            response = valueStr;
        }
        LogUtil.json(response);
        try {//规范正常的接口
            BaseModel baseModel = gson.fromJson(response, BaseModel.class);
            if (!baseModel.isSuccessInvalid()) {
                value.close();
                throw new ApiException(baseModel.getCode(), baseModel.getMsg());
            }
        } catch (JsonSyntaxException e) {//规范不正常的接口(即json解析错误)
            AddressModel addressModel = gson.fromJson(response, AddressModel.class);
        }

        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream);
        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
